import { ref } from 'vue';
import AddressModel from '@/utils/models/AddressModel';
import { AddressData } from '@/utils/models/data/AddressData';

export default class AddressViewModel {
	// 静态属性，用于保存类的唯一实例
	private static instance : AddressViewModel;
	isSelect = false;
	editAddressData = ref<AddressData>(new AddressData());
	defaultAddressData = ref<AddressData>(new AddressData());
	selectAddressData = ref<AddressData>(new AddressData());
	dataArray = ref<AddressData[]>([]);  // 保存地址数据
	page = 1;  // 当前页码

	// 构造函数设为私有，防止外部通过 new 实例化
	private constructor() {
		console.log('this.defaultAddressData =', this.defaultAddressData);
		console.log('this.dataArray.value =', this.dataArray.value);
		if (!this.defaultAddressData.value.id) {
			this.getList();
		}
	}

	// 获取实例的静态方法，保证返回的是单例
	public static getInstance() : AddressViewModel {
		if (!this.instance) {
			this.instance = new AddressViewModel();
		}
		return this.instance;
	}

	// 获取地址列表的方法
	public async getList() : Promise<AddressData[]> {
		return new Promise(async (resolve, reject) => {
			try {
				const addressModel = new AddressModel();  // 实例化 AddressModel
				const result = await addressModel.getList(this.page);  // 获取地址列表
				if (this.page === 1) {
					this.dataArray.value.length = 0;  // 如果是第一页，清空现有数据
				}
				if (result.length) {
					this.page++;
					this.dataArray.value.push(...result);  // 将新数据追加到数组中
				}
				this.dataArray.value.forEach((item) => {
					console.log('item.defaultAddress== ', item.defaultAddress);
					if (item.defaultAddress === '1') {
						this.defaultAddressData.value = item;
						this.selectAddressData.value = item;
					}
				});
				resolve(this.dataArray.value);  // 返回数据
			} catch (error) {
				reject(error.message || '获取失败');  // 处理错误
			} finally {
				console.log('请求完成');
			}
		});
	}

	// 获取地址列表的方法
	public async getDetail(id : string) : Promise<AddressData[]> {
		return new Promise(async (resolve, reject) => {
			try {
				const res = new AddressModel().getDetail(id);
				resolve(res);  // 返回数据
			} catch (error) {
				reject(error.message || '获取失败');  // 处理错误
			} finally {
				console.log('请求完成');
			}
		});
	}

	saveAddress() {
		if (!this.editAddressData.value.contactPerson) {
			uni.showToast({
				icon: 'none',
				title: '请输入姓名'
			});
			return;
		}
		if (!this.editAddressData.value.contactPhone) {
			uni.showToast({
				icon: 'none',
				title: '请输入手机号'
			});
			return;
		}
		if (!this.editAddressData.value.detailAddress) {
			uni.showToast({
				icon: 'none',
				title: '请选择地址'
			});
			return;
		}
		if (!this.editAddressData.value.address) {
			uni.showToast({
				icon: 'none',
				title: '请输入详细地址'
			});
			return;
		}
		const addressModel = new AddressModel();  // 实例化 AddressModel
		addressModel.updateDetail(this.editAddressData.value).then(() => {
			if (this.editAddressData.value.id) {
				let targetElement = this.dataArray.value.find(item => item.id === this.editAddressData.value.id);
				if (targetElement) {
					targetElement = this.editAddressData.value;
				} else {
					this.dataArray.value.push(this.editAddressData.value);
				}
				if (targetElement?.id !== this.defaultAddressData.value.id) {
					this.defaultAddressData.value.defaultAddress = '0';
					this.defaultAddressData.value = this.editAddressData.value;
				}
			} else {
				this.page = 1;
				this.getList();
			}
			uni.navigateBack();
		});
	}

	deleteAddress() {
		const addressModel = new AddressModel();  // 实例化 AddressModel
		let addressId = this.editAddressData.value.id ?? 0;
		uni.showModal({
			title: '提示',
			content: `是否删除地址？`,
			confirmColor: '#CBAB7C',
			success: (res) => {
				if (res.confirm) {
					addressModel.delete(addressId).then(() => {
						const targetIndex = this.dataArray.value.findIndex(item => item.id === addressId);
						if (targetIndex !== -1) {
							this.dataArray.value.splice(targetIndex, 1);  // 移除 targetElement
							uni.navigateBack();
						}
					});
				}
			}
		});
	}

	selectItem(data : AddressData) {
		console.log("选择了 ", data);
		if (this.isSelect) {
			this.selectAddressData.value = data;
			uni.navigateBack();
		}
	}

	onDefaultChange(event : any) {
		console.log("复选框 =", event.detail.value.length);
		const isChecked = event.detail.value.length > 0;
		console.log("this.editAddressData.value =", this.editAddressData.value);
		// 根据选中状态更新 defaultAddress
		this.editAddressData.value.defaultAddress = isChecked ? '1' : '0';
	}

	onBlur = (event : { detail : { value : string } }) => {
		this.editAddressData.value.contactPerson = event.detail.value;
	};
}